﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MindFactorial.LaunchPoint.Console.Library;
using MindFactorial.LaunchPoint.Common;
using Microsoft.Win32;
using System.Configuration;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;   

namespace GeneralSettings.Plugin.Library
{
    /// <summary>
    /// Interaction logic for GeneralSettingsContent.xaml
    /// </summary>
    [PluginSurfacePresenter(SurfaceTarget.Content)]
    public partial class GeneralSettingsContent
    {        
        Configuration _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        
        NameValueCollection _app_settings = ConfigurationManager.AppSettings;

        public GeneralSettingsContent()
        {
            InitializeComponent();

            this.btnRootFolderPath.Click += new RoutedEventHandler(btnRootFolderPath_Click);
            this.btnPDDFolderPath.Click += new RoutedEventHandler(btnPDDFolderPath_Click);
            this.btnSubmit.Click += new RoutedEventHandler(btnSubmit_Click);

            ConfigurationManager.RefreshSection("appSettings");
            if (_app_settings["RootFolderPath"] != null)
            {
                txtRootFolderPath.Text = _app_settings["RootFolderPath"].ToString();
            }

            if (_app_settings["PPDFolderPath"] != null)
            {
                txtPDDFolderPath.Text = _app_settings["PPDFolderPath"].ToString();
            }
           
        }

        /// <summary>
        /// Saves to the configuration file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                if (ValidateInput())
                {

                    bool is_updated = false; 
                    if (txtRootFolderPath.Text.Trim() != "")
                    {
                        AddPropToAppSettings("RootFolderPath", txtRootFolderPath.Text);
                        is_updated = true; 
                    }
                    if (txtPDDFolderPath.Text.Trim() != "")
                    {
                        AddPropToAppSettings("PPDFolderPath", txtPDDFolderPath.Text);
                        is_updated = true;
                    }
                    if (is_updated)
                    {
                        string parameter = string.Format("<Data><RootFolderPath><Key>{0}</Key><Value>{1}</Value></RootFolderPath><PPDFolderPath><Key>{2}</Key><Value>{3}</Value></PPDFolderPath></Data>", "RootFolderPath", txtRootFolderPath.Text.Trim(), "PPDFolderPath", txtPDDFolderPath.Text.Trim());
                        string response = this.PluginContext.RuntimeContext.RulesEngine.Rule["ProductTransferAdapter", "UpdateConfigurationInfo"].Execute(parameter);
                        _config.Save(ConfigurationSaveMode.Modified);

                        System.Windows.MessageBox.Show("Configuration File Updation Successful!");
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("Input fields cannot be empty");
                    }
                }

            }
            catch (Exception Ex)
            {
                Logger.Log("84327072-0F6A-41a5-9CF3-F8DFC9CB67AB", Ex);             

            }

        }

        private bool ValidateInput()
        {
            if (txtRootFolderPath.Text.Trim() != "")
            {
                if (!System.IO.Directory.Exists(txtRootFolderPath.Text))
                {
                    System.Windows.MessageBox.Show(String.Format("The folder {0} doesn't exist ", txtRootFolderPath.Text));
                    return false;
                }
            }

            if (txtPDDFolderPath.Text.Trim() != "")
            {
                if (!System.IO.Directory.Exists(txtPDDFolderPath.Text))
                {
                    System.Windows.MessageBox.Show(String.Format("The folder {0} doesn't exist ", txtPDDFolderPath.Text));
                    return false;
                }
            }
            return true; 
        }

        /// <summary>
        /// This will add key, value to the AppSettings section of the configuration
        /// object
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Value</param>
        private void AddPropToAppSettings(string key, string val)
        {

            if (_app_settings[key] == null)
            {
                _config.AppSettings.Settings.Add(key, val);
            }
            else
            {
                _config.AppSettings.Settings.Remove(key);
                _config.AppSettings.Settings.Add(key, val);

            }
        }

        private void btnRootFolderPath_Click(object sender, RoutedEventArgs e)
        {
            BrowseFolder("Root");
        }



        private void btnPDDFolderPath_Click(object sender, RoutedEventArgs e)
        {
            BrowseFolder("Pdd");
        }

        /// <summary>
        /// This function will allow you to browse and set the Folder Path
        /// </summary>
        /// <param name="name">Folder Name</param>
        private void BrowseFolder(string name)
        {
            try
            {
                string folder;
                FolderBrowserDialog dlg = new FolderBrowserDialog();

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    folder = dlg.SelectedPath;
                    switch (name)
                    {
                        case "Root": txtRootFolderPath.Text = folder;
                          
                            break;

                        case "Pdd": txtPDDFolderPath.Text = folder;
                            
                            break;

                        default:
                            break;


                    }

                }


            }
            catch (Exception Ex)
            {
                Logger.Log("BB6050E7-EFDD-43bc-8384-31FCF4600A28", Ex);                
            }

         }



    }
}
